<section class="content-header">
  <h1>&nbsp;</h1>
  <ol class="breadcrumb">
    <li><a><i class="fa fa-dashboard"></i>信息管理</a></li>
    <li class="active"><a>车队管理</a></li>
  </ol>
</section>
<!-- Main content -->
<section class="content" id="deviceContent">
  <div class="row">
    <div class="col-xs-12">
      <div class="box">
        <div class="box-body">
			<!-- 搜索条件 -->
			<table style="width:100%;height:500px;" border="0">
				<tr>
					<td align="left" style="width:30%;">
					    <label for="account" class="col-sm-12 control-label">公司车队列表</label>
					    <div class="input-group" style="width:320px;">
				          <input type="text" id="sel_company" class="form-control" placeholder="查找公司">
				              <span class="input-group-btn">
				                <button id="searchBtn" name="searchBtn" class="btn btn-flat" onClick=><i class="fa fa-search"></i></button>
				              </span>
				        </div>
						<div class="zTreeDemoBackground left">
							<ul id="treeDemo" class="ztree" style="width:320px;"></ul>
						</div>
					</td>
					<td align="left" valign="top" style="width:30%;border:1px solid #ececec">
						<label for="account" class="col-sm-12 control-label">已分配车辆</label>
					    <div class="input-group" style="width:320px;">
				          <input type="text" id="sel_vehicle" class="form-control" placeholder="已分配车辆">
				              <span class="input-group-btn">
				                <button id="searchBtn" name="searchBtn" class="btn btn-flat" onClick=><i class="fa fa-search"></i></button>
				              </span>
				        </div>
						<table id="vehicle" class="table table-bordered table-condensed table-hover table-striped">
				             <thead>
				             <tr>
				               <th><input type='checkbox' class='minimal' id="vehicle_check_all"/></th>
				               <th>序号</th>
				               <th>车牌号</th>
				               <th>所属公司</th>
				             </tr>
				             </thead>
				             <tbody>
				              </tbody>
				        </table>
					</td>
					<td align="center" valign="middle" style="width:10%;">
						<button class="btn btn-success btn-small" onclick="removeIn()">&lt;&lt;移至车队</button>&nbsp;<br/><br/>
						<button class="btn btn-success btn-small" onclick="removeOut()">移出车队&gt;&gt;</button>&nbsp;
					</td>
					<td align="left" valign="top" style="width:30%;border:1px solid #ececec">
						<label for="account" class="col-sm-12 control-label">未分配车辆</label>
					    <div class="input-group" style="width:320px;">
				          <input type="text" id="sel_vehicle_no" class="form-control" placeholder="未分配车辆">
				              <span class="input-group-btn">
				                <button id="searchBtn" name="searchBtn" class="btn btn-flat" onClick=><i class="fa fa-search"></i></button>
				              </span>
				        </div>
						<table id="vehicle_no" class="table table-bordered table-condensed table-hover table-striped">
				             <thead>
				             <tr>
				               <th><input type='checkbox' class='minimal' id="vehicle_no_check_all"/></th>
				               <th>序号</th>
				               <th>车牌号</th>
				               <th>所属公司</th>
				             </tr>
				             </thead>
				             <tbody>
				              </tbody>
				        </table>											
					</td>
				</tr>
				<tr>
					<td colspan="4" style="height:70px;">
						<input type="hidden" class="form-control" id="id"/>
						<input type="hidden" class="form-control" id="name"/>
						<input type="hidden" class="form-control" id="levelFlag"/>
						<input type="hidden" class="form-control" id="p_id"/>
						<input type="hidden" class="form-control" id="p_name"/>
						<input type="hidden" class="form-control" id="isChildren"/>
						<button class="btn btn-success btn-small" onclick="showDialog('insert');">添加车队</button>&nbsp;
						<button class="btn btn-success btn-small" onclick="showDialog('update');">编辑车队</button>&nbsp;
						<button class="btn btn-success btn-small" onclick="showDialog('delete');">删除车队</button>&nbsp;
						<button class="btn btn-success btn-small" onclick="showDialog('remove');">移动车队</button>&nbsp;
					</td>
				</tr>
				<tr>
					<td colspan="4">
						<ul class="list">
							<li>您可以使用拖动的方式移动车队，车队只能移动到所在公司的下级公司及其车队，公司下车队可互相移动；</li>
							<li>点击公司，可以刷新未分配车辆；点击车队，可以刷新已分配车辆；必须先将车辆移除车队，才能分配到其他车队；车辆只能分配到所在公司下的车队；</li>
						</ul>
					</td>
				</tr>
			</table>
         	</div>
       	 </div>
      </div>
   </div>
</section>
<div class="modal fade" id="infoModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="infoModalTitle"></h4>
            </div>
            <form class="form-horizontal" id="defaultForm">
	            <div class="modal-body">
	           		<div class="box-body">
	         			<div class="form-group">
	              		  <label class="col-sm-2 control-label">车队名称</label>
		                  <div class="col-sm-8">
		                    <input type="text" class="form-control" id="team_name" name="team_name" maxlength="50"/>
		                  </div>
		                </div>
	              		  <div class="form-group">
		                   <label class="col-sm-2 control-label">所属公司</label>
		                    <div class="col-sm-8">
		                  		<input type="hidden" class="form-control" id="team_company_id" disabled/>
		                    	<input type="text" class="form-control" id="team_company_name" disabled/>
		                    </div>
		                  </div>	                		
	           		</div>
	            </div>
	            <div class="modal-footer">
	            	<input type="hidden" id="infoId"/>
	            	<button type="button" class="btn btn-primary" id="saveInfoBtn">保存</button>
	                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	            </div>
           </form>
        </div>
    </div>
</div> 
<!-- 移动车队 -->
<div class="modal fade" id="removeModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">移动车队</h4>
            </div>
            <div class="modal-body">
            	<form class="form-horizontal">
              		<div class="box-body">
               			<div class="form-group">
               			  <label for="account" class="col-sm-2 control-label">所选车队</label>
		                  <div class="col-sm-8">
		                    <input type="hidden" class="form-control" id="remove_id" disabled/>
		                    <input type="text" class="form-control" id="remove_name" disabled/>
		                    <input type="hidden" class="form-control" id="remove_old_p_id" disabled/>
		                  </div>
		                </div>
               			<div class="form-group">
		                  <label class="col-sm-2 control-label">选择公司</label>
		                  <div class="col-sm-8">
								<div class="zTreeDemoBackground left">
									<ul id="tree_removeTeam" class="ztree" style="width:355px;"></ul>
								</div>
		                   </div>
		                </div>	                		
            		</div>
           		</form>
            </div>
            <div class="modal-footer">
				<input type="hidden" class="form-control" id="remove_levelFlag"/>
				<input type="hidden" class="form-control" id="remove_p_id"/>
				<input type="hidden" class="form-control" id="remove_p_name"/>
            	<button type="button" class="btn btn-primary" onclick="removeInfo()">保存</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div> 
<script type="text/javascript">
	$(function(){ 
	  onLoadCompanyTree();
	  $('#defaultForm').bootstrapValidator({
	        message: '此值无效',
	        feedbackIcons: {
	            valid: 'glyphicon glyphicon-ok',
	            invalid: 'glyphicon glyphicon-remove',
	            validating: 'glyphicon glyphicon-refresh'
	        },
	        fields: {
	        	team_name: {
	                validators: {
	                    notEmpty: {
	                        message: '不能为空'
	                    }
	                }
	            }
	        }
	    });
	    $("#saveInfoBtn").on("click", function(){
		    var bootstrapValidator = $('#defaultForm').data('bootstrapValidator');
	        bootstrapValidator.validate();
	        if(bootstrapValidator.isValid()){
	            saveInfo();
	        }
		 });		 
	});
   function showDialog(opStr){
	   var levelFlag = $.trim($("#levelFlag").val());
	   if(levelFlag==""){
		   alert("请选择公司或车队结点！");
		   return false;
	   }
	   var id = $.trim($("#id").val());
	   var name = $.trim($("#name").val());
	   var p_id = $.trim($("#p_id").val());
	   var p_name = $.trim($("#p_name").val());
	   var isChildren = $.trim($("#isChildren").val());
	   if(opStr=="insert"){//只能在公司下面增加车队
		   if(levelFlag=="2"){
			   alert("只能在公司下面增加车队，请选择公司结点！");
			   return false;
		   }
		   $("#infoId").val("-1");
		   $("#team_name").val("");
		   $("#team_company_id").val(id);
		   $("#team_company_name").val(name);	
		   $("#infoModalTitle").text("添加车队");
		   $("#infoModal").modal('show');
	   }
	   if(opStr=="update"){//不能修改公司，只能修改车队结点
		   if(levelFlag=="1"){
			   alert("不能修改公司信息，请选择车队结点！");
			   return false;
		   }
		   $("#infoId").val(id);
		   $("#team_name").val(name);
		   $("#team_company_id").val(p_id);
		   $("#team_company_name").val(p_name);	
		   $("#infoModalTitle").text("编辑车队");
		   $("#infoModal").modal('show');
	   }
	   if(opStr=="delete"){//只能删除车队，而且需要判断此车队下面是否还有子结点
		   if(levelFlag=="1"){
			   alert("不能修改公司信息，请选择车队结点！");
			   return false;
		   }
		   if(isChildren=="0"){
			   alert("此车队还存在车辆结点信息，无法删除！");
			   return false;
		   }
		   deleteInfo(id);
	   }
	   if(opStr=="remove"){//只能移动车队
		   if(levelFlag=="1"){
			   alert("不能修改公司信息，请选择车队结点！");
			   return false;
		   }
		   $("#remove_id").val(id);
		   $("#remove_name").val(name);
		   $("#remove_old_p_id").val(p_id);
		   onLoadCompanyTree_removeTeam();
		   $("#removeModal").modal('show');
	   }	   
   }
   function saveInfo(){
	    var name = $.trim($("#team_name").val());
	    var company_id = $.trim($("#team_company_id").val());
	    var data = {id:$("#infoId").val(), name:name, company_id:company_id};
	    $.ajax({
	        url: "${request.contextPath}/team/saveOrUpdateInfo",
	        type: "post",
	        async: false,
	        data: data,
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success){
	            		location.reload();
	            	}else{
	            		alert("数据出错!");
	            		return false;
	            	}
	            }
	        },
	        error: function () { }
	    });
   }
   function deleteInfo(id){
	   if(id){
		   CvMsg.confirm("警告","数据删除后将无法还原！是否删除？",function(){
			   $.ajax({
				   url: "${request.contextPath}/team/deleteInfo",
					type : "post",
					data : {id:id},
					success : function(data) {
						if (data.success) {
							location.reload();
						} else {
		            		alert("数据出错!");
		            		return false;
						}
					}
				}); 
		   });
	   }
	}
   function onLoadCompanyTree(){
	   var imagePath = "${request.contextPath}/assets/dist/img/imagesAmap/";
	   $.ajax({
			url : "${request.contextPath}/user/getTreeOrgTeam",
			type : "post",
			success : function(data) {
				if (data.success && data.other) {
				   var setting = {
				   		view: {
				   			dblClickExpand: true
				   		},
				   		data: {
				   			simpleData: {
				   				enable: true
				   			}
				   		},
				   		callback: {
				   			onClick: onClick
				   		}
				   	};
				   var treeData = formatTreeImage(data.other);
			       $.fn.zTree.init($("#treeDemo"), setting, treeData);
			       $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);//展开
				}
			}
		});
   }
  	function onClick(e, treeId, treeNode) {
   		var zTree = $.fn.zTree.getZTreeObj("treeDemo"),nodes = zTree.getSelectedNodes();
   		if(nodes && nodes.length>0){
   			var id = nodes[0].id;
   			var name = nodes[0].name;
   	   		if(treeNode.getParentNode()){
   	   	   		$("#p_id").val(treeNode.getParentNode().id);
   	   	   		$("#p_name").val(treeNode.getParentNode().name);
   	   		}else{
   	   	   		$("#p_id").val("-1");
   	   	   		$("#p_name").val("-1");  			
   	   		}
   			var levelFlag = nodes[0].levelFlag;
   			$("#levelFlag").val(levelFlag);
   			$("#name").val(name);
   			if(levelFlag=="2"){
   	   			$("#id").val(id.split("_")[1]);
   			}else{
   	   			$("#id").val(id);
   			}
   	   		if(treeNode.children && treeNode.children.length>=1){
   	   			$("#isChildren").val("0");
   	   		}else{
   	   			$("#isChildren").val("1");
   	   		}
   	   	    //console.log($("#id").val()+"-----------"+$("#name").val()+"============="+$("#p_id").val()+"============="+$("#p_name").val()+"$$$$$$$$$$$$$$$$$$$$$$"+levelFlag);
   	   		//右侧显示车辆列表
   	   	    showVehicle();
   		}
   	}
  	function showVehicle(){
  		var levelFlag = $("#levelFlag").val();
  		var id = $("#id").val();
  		var name = $("#name").val();
  		var p_id = $("#p_id").val();
   		if(levelFlag=="1"){//所选的是公司
   			$("#vehicle tbody").empty();
   			getVehicleByCompanyIdNoTeam(id,name); //所属公司但未分配车队的列表
   		}
   	    if(levelFlag=="2"){//所选的是车队，加载其车辆列表
   	        getVehicleByTeamId(id,name); //已分配车队的车辆列表
   	  		getVehicleByCompanyIdNoTeam(p_id,name); //所属公司但未分配车队的列表
   		}
  	}
  	function showMenu() {
   		var cityObj = $("#pid");
   		var cityOffset = $("#pid").offset();
   		$("#menuContent").slideDown("fast");
   		$("body").bind("mousedown", onBodyDown);
   	}
   	function hideMenu() {
   		$("#menuContent").fadeOut("fast");
   		$("body").unbind("mousedown", onBodyDown);
   	}
   	function onBodyDown(event) {
   		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
   			hideMenu();
   		}
   	}
   	//移动车队对话框中的_公司车队Team
    function onLoadCompanyTree_removeTeam(){
    	var setting = {
	   		view: {
	   			dblClickExpand: true
	   		},
	   		data: {
	   			simpleData: {
	   				enable: true
	   			}
	   		},
	   		callback: {
	   			onClick: onClick_removeTeam
	   		}
	   };
 	   $.ajax({
			url : "${request.contextPath}/user/getTreeOrg",
			type : "post",
			success : function(data) {
				if (data.success && data.other) {
				   var setting = {
				   		view: {
				   			dblClickExpand: true
				   		},
				   		data: {
				   			simpleData: {
				   				enable: true
				   			}
				   		},
				   		callback: {
				   			onClick: onClick
				   		}
				   	};
				   var treeData = formatTreeImage(data.other);
			       $.fn.zTree.init($("#tree_removeTeam"), setting, treeData);
			       $.fn.zTree.getZTreeObj("tree_removeTeam").expandAll(true);//展开
				}
			}
		});    	
    }
  	function onClick_removeTeam(e, treeId, treeNode) {
   		var zTree = $.fn.zTree.getZTreeObj("tree_removeTeam"),nodes = zTree.getSelectedNodes();
   		if(nodes && nodes.length>0){
   			var remove_levelFlag = nodes[0].levelFlag;
   			$("#remove_levelFlag").val(remove_levelFlag);
   	   		if(treeNode.getParentNode()){
   	   	   		$("#remove_p_id").val(treeNode.getParentNode().id);
   	   	   		$("#remove_p_name").val(treeNode.getParentNode().name);
   	   		}else{
   	   	   		$("#remove_p_id").val("-1");
   	   	   		$("#remove_p_name").val("-1");  			
   	   		}
   		}
   	}
    function removeInfo(){
 	   var remove_levelFlag = $.trim($("#remove_levelFlag").val());
 	   if(remove_levelFlag==""){
 		   alert("请选择公司结点！");
 		   return false;
 	   }
 	   var remove_p_id = $.trim($("#remove_p_id").val());
 	   var remove_p_name = $.trim($("#remove_p_name").val());
 	   var remove_old_p_id = $.trim($("#remove_old_p_id").val());
	   if(remove_levelFlag=="2"){
		   alert("只能在公司下面移动车队，请选择公司结点！");
		   return false;
	   }
	   if(remove_p_id!=remove_old_p_id){
		   alert("车队只能向所在公司、子公司之间移动！");
		   return false;
	   }
    }
    //已分配车队的车辆列表
   	function getVehicleByTeamId(team_id,name){
   		$("#vehicle tbody").empty();
	    $.ajax({
	        url: "${request.contextPath}/team/getVehicleByTeamId",
	        type: "post",
	        async: false,
	        data: {team_id:team_id},
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success && data.msg){
	            		var item = data.msg;
	            		var html = "";
	            		for(var i=0;i<item.length;i++){
	            			html+="<tr><td><input id='vehicle_check' name='vehicle_check' type='checkbox' class='minimal' value='"+item[i].id+"'/></td><td>"+(i+1)+"</td><td>"+item[i].vehid+"</td>"+"<td>"+name+"</td></tr>";
	            		}
	            		$("#vehicle tbody").html(html);
	            	}
	            }
	        },
	        error: function () { }
	    });
   	}
    //所属公司但未分配车队的列表
   	function getVehicleByCompanyIdNoTeam(company_id,name){
    	//console.log("------------>>>getVehicleByCompanyIdNoTeam"+company_id+"---"+name);
    	$("#vehicle_no tbody").empty();
	    $.ajax({
	        url: "${request.contextPath}/team/getVehicleByCompanyIdNoTeam",
	        type: "post",
	        async: false,
	        data: {company_id:company_id},
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success && data.msg){
	            		var item = data.msg;
	            		var html = "";
	            		for(var i=0;i<item.length;i++){
	            			html+="<tr><td><input id='vehicle_no_check' name='vehicle_no_check' type='checkbox' class='minimal' value='"+item[i].id+"'/></td><td>"+(i+1)+"</td><td>"+item[i].vehid+"</td>"+"<td>"+name+"</td></tr>";
	            		}
	            		$("#vehicle_no tbody").html(html);
	            	}
	            }
	        },
	        error: function () { }
	    });
   	}
    //移至车队
    function removeIn(){
    	var chkIds = ""; 
    	$('input[id="vehicle_no_check"]:checked').each(function(){ 
    		chkIds += $(this).val()+",";
    	}); 
    	if(chkIds==""){
    		alert("请选择未分配车辆");
    		return false;
    	}
    	if($("#levelFlag").val()!="2"){
    		alert("请选择车队结点！");
    		return false;
    	}
	    $.ajax({
	        url: "${request.contextPath}/team/removeInTeam",
	        type: "post",
	        async: false,
	        data: {team_id:$("#id").val(), chkIds:chkIds},
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success){
	            		showVehicle();
	            	}else{
	            		alert("数据出错!");
	            		return false;
	            	}
	            }
	        },
	        error: function () { }
	    });
    }
    //移出车队
    function removeOut(){
    	var chkIds = ""; 
    	$('input[id="vehicle_check"]:checked').each(function(){ 
    		chkIds += $(this).val()+",";
    	}); 
    	if(chkIds==""){
    		alert("请选择已分配车辆");
    		return false;
    	}
	    $.ajax({
	        url: "${request.contextPath}/team/removeOutTeam",
	        type: "post",
	        async: false,
	        data: {team_id:$("#id").val(), chkIds:chkIds},
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success){
	            		showVehicle();
	            	}else{
	            		alert("数据出错!");
	            		return false;
	            	}
	            }
	        },
	        error: function () { }
	    });    	
    }
</script>
